package com.wedu.modules.dss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wedu.common.utils.PageUtils;
import com.wedu.common.utils.Query;
import com.wedu.common.utils.R;
import com.wedu.modules.dss.dao.DeviceInformationDao;
import com.wedu.modules.dss.dao.MaintenanceWarningDao;
import com.wedu.modules.dss.entity.dto.MaintenanceWarningDTO;
import com.wedu.modules.dss.entity.DeviceInformationEntity;
import com.wedu.modules.dss.entity.MaintenanceRecordsEntity;
import com.wedu.modules.dss.entity.MaintenanceWarningEntity;
import com.wedu.modules.dss.service.MaintenanceRecordsService;
import com.wedu.modules.dss.service.MaintenanceWarningService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("MaintenanceWarningService")
public class MaintenanceWarningServiceImpl extends ServiceImpl<MaintenanceWarningDao, MaintenanceWarningEntity> implements MaintenanceWarningService {

    @Autowired
    private DeviceInformationDao deviceInformationDao;

    @Autowired
    private MaintenanceWarningDao maintenanceWarningDao;

    @Autowired
    private MaintenanceRecordsService maintenanceRecordsService;

    @Autowired
    private MaintenanceWarningService maintenanceWarningService;
    //分页工具类，查询没被删除的数据
    @Override
    public PageUtils queryPageWarning(Map<String, Object> params) {
        String deviceName = (String) params.get("deviceName");
        Integer maintenanceStatus = (Integer) params.get("maintenanceStatus");
        Date noticeTime = (Date) params.get("NoticeTime");
        Date date = new Date();

        MPJLambdaWrapper<DeviceInformationEntity> wrapper = new MPJLambdaWrapper<DeviceInformationEntity>()
                .select(DeviceInformationEntity::getId,DeviceInformationEntity::getDeviceId,DeviceInformationEntity::getWorkshopName,DeviceInformationEntity::getDeviceType,DeviceInformationEntity::getDeviceName,DeviceInformationEntity::getDeviceModel)
                .select(MaintenanceWarningEntity::getMaintenancePlan,MaintenanceWarningEntity::getMaintenanceDueTime,MaintenanceWarningEntity::getNoticeTime,MaintenanceWarningEntity::getMaintenanceStatus)
                .leftJoin(MaintenanceWarningEntity.class,MaintenanceWarningEntity::getDeviceId,DeviceInformationEntity::getDeviceId)
                .like(StringUtils.isNotBlank(deviceName),"device_name",deviceName)
                .eq("maintenance_status",-1);


        IPage<MaintenanceWarningEntity> page = this.page(
                new Query<MaintenanceWarningEntity>().getPage(params),
                new QueryWrapper<MaintenanceWarningEntity>()
                .eq("is_deleted",0)
                .orderByDesc("create_time")
        );

        IPage<MaintenanceWarningDTO> DTOpage = new Page<>();
        List<MaintenanceWarningDTO> DTOlist = deviceInformationDao.selectJoinList(MaintenanceWarningDTO.class,wrapper);

        //如果当前状态为已保养，到当前时间在预警时间后则修改状态为未保养
        for (MaintenanceWarningDTO maintenanceWarningDTO : DTOlist) {
            if (maintenanceWarningDTO.getMaintenanceStatus() == null) {
                continue;
            }else if (maintenanceWarningDTO.getMaintenanceStatus() == 1){//
                if (date.after(maintenanceWarningDTO.getNoticeTime())){
                     MaintenanceWarningEntity maintenanceWarningEntity;
                     maintenanceWarningEntity = maintenanceWarningService.getDevice(maintenanceWarningDTO.getDeviceId());
                     maintenanceWarningEntity.setMaintenanceStatus(-1);
                     maintenanceWarningDao.updateById(maintenanceWarningEntity);
                }
            }
        }
        List<MaintenanceWarningDTO> list = deviceInformationDao.selectJoinList(MaintenanceWarningDTO.class,wrapper);

        DTOpage.setTotal(page.getTotal());
        DTOpage.setSize(page.getSize());
        DTOpage.setRecords(list);
        DTOpage.setCurrent(page.getCurrent());
        DTOpage.setPages(page.getPages());

        return new PageUtils(DTOpage);
    }


    @Override
    public R saveWarning(MaintenanceWarningEntity maintenanceWarningEntity) {
        //添加所选方案与设备id，根据方案添加时间，如：方案一保养时间为当前+15天，预警时间为当前时间+12天
        //获取前端选择的主表中的设备id

        //查询M表中的id字段
        QueryWrapper<MaintenanceWarningEntity> wrapper = new QueryWrapper<MaintenanceWarningEntity>();
        List<MaintenanceWarningEntity> list = maintenanceWarningDao.selectList(wrapper);
        List<String> deviceIdlist = new ArrayList<>();
        //获取他的保养剂计划
        String maintenancePlan = maintenanceWarningEntity.getMaintenancePlan();
        for (MaintenanceWarningEntity warningEntity : list) {
            deviceIdlist.add(warningEntity.getDeviceId());
        }
        if (deviceIdlist.contains(maintenanceWarningEntity.getDeviceId())) {
            return R.error(500, "设备已存在");
        } else {
            if (maintenancePlan.equals("1")){//如果方案一：当前时间+X天 预警时间+(X-Y)天 X=15 Y=3
                Integer x = maintenanceWarningEntity.getMaintenanceCycle();
                Integer y = maintenanceWarningEntity.getAdvanceTime();
                Date date1 = new Date();
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.DATE,x);/***/
                date1 = calendar1.getTime();
                maintenanceWarningEntity.setMaintenanceDueTime(date1);
                Date date2 = new Date();
                Calendar calendar2 = Calendar.getInstance();
                calendar2.add(Calendar.DATE,(x-y));/***/
                date2 = calendar2.getTime();
                maintenanceWarningEntity.setNoticeTime(date2);
                Date now = new Date();
                if (now.before(date2)){
                    maintenanceWarningEntity.setMaintenanceStatus(1);
                }else if (now.after(date2)){
                    maintenanceWarningEntity.setMaintenanceStatus(0);
                }else {
                    maintenanceWarningEntity.setMaintenanceStatus(-1);
                }

            }else if (maintenancePlan.equals("2")){
                //如果方案二：当前时间+X小时  X=120
                Integer x = maintenanceWarningEntity.getMaintenanceCycle();
                Date date3 = new Date();
                Calendar calendar3 = Calendar.getInstance();
                calendar3.add(Calendar.HOUR,x);/***/
                date3 = calendar3.getTime();
                maintenanceWarningEntity.setMaintenanceDueTime(date3);
                maintenanceWarningEntity.setNoticeTime(date3);
                Date now = new Date();
                if (now.before(date3)){
                    maintenanceWarningEntity.setMaintenanceStatus(1);
                }else if (now.after(date3)){
                    maintenanceWarningEntity.setMaintenanceStatus(0);
                }else {
                    maintenanceWarningEntity.setMaintenanceStatus(-1);

                }
            }
            this.save(maintenanceWarningEntity);
            return R.ok();
        }
    }


    @Override
    public void updateWarning(MaintenanceWarningEntity maintenanceWarningEntity) {
        this.updateById(maintenanceWarningEntity);
    }

    @Override
    public MaintenanceWarningEntity getDevice(String deviceId) {
        QueryWrapper<MaintenanceWarningEntity> wrapper = new QueryWrapper<MaintenanceWarningEntity>()
                .eq("device_id",deviceId);
        MaintenanceWarningEntity maintenanceWarningEntity = maintenanceWarningDao.selectOne(wrapper);
        return maintenanceWarningEntity;
    }

    @Override
    public void maintenance(String[] deviceId,Long id) {
        for (String s : deviceId) {
            QueryWrapper<MaintenanceWarningEntity> wrapper = new QueryWrapper<MaintenanceWarningEntity>()
                    .eq("device_id",s);
            MaintenanceWarningEntity maintenanceWarningEntity = maintenanceWarningDao.selectOne(wrapper);
            maintenanceWarningEntity.setMaintenanceStatus(0);
            MaintenanceRecordsEntity maintenanceRecordsEntity = new MaintenanceRecordsEntity();
            maintenanceRecordsEntity.setDeviceId(s);
            Date date = new Date();
            //添加在记录表中
            maintenanceRecordsEntity.setMaintenanceTime(date);
            maintenanceRecordsEntity.setUserId(id);
            maintenanceRecordsEntity.setCreateBy(id);
            maintenanceRecordsEntity.setCreateTime(date);
            maintenanceRecordsService.save(maintenanceRecordsEntity);
            if (maintenanceWarningEntity.getMaintenancePlan().equals("1")){
                Integer x = maintenanceWarningEntity.getMaintenanceCycle();
                Integer y = maintenanceWarningEntity.getAdvanceTime();
                Date date1 = new Date();
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.DATE,x);
                date1 = calendar1.getTime();
                maintenanceWarningEntity.setMaintenanceDueTime(date1);

                Date date2 = new Date();
                Calendar calendar2 = Calendar.getInstance();
                calendar2.add(Calendar.DATE,(x-y));
                date2 = calendar2.getTime();
                maintenanceWarningEntity.setNoticeTime(date2);
            }else if (maintenanceWarningEntity.getMaintenancePlan().equals("2")){
                Integer x = maintenanceWarningEntity.getMaintenanceCycle();
                Date date1 = new Date();
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.DATE,x);
                date1 = calendar1.getTime();
                maintenanceWarningEntity.setMaintenanceDueTime(date1);
                maintenanceWarningEntity.setNoticeTime(date1);

            }
            maintenanceWarningDao.updateById(maintenanceWarningEntity);//塞实体类
        }

    }

}
